package com.whz.generic.serializer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.util.IOUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;

/**
 * FastJson 序列化方式
 *
 * @author whz
 */
@Slf4j
public class FastJsonRedisSerializer extends AbstractRedisSerializer {
    private static final ParserConfig DEFAULT_REDIS_CONFIG = new ParserConfig();
    public static final Feature[] FEATURES = new Feature[0];

    static {
        DEFAULT_REDIS_CONFIG.setAutoTypeSupport(true);
    }

    @Override
    public byte[] serialize(Object value) {
        if (value == null) {
            return SerializationUtils.EMPTY_ARRAY;
        }
        return JSON.toJSONBytes(value, SerializerFeature.WriteClassName);
    }

    @Override
    public Object deserialize(byte[] bytes) {
        return deserialize(bytes, Object.class);
    }

    public <T> T deserialize(byte[] bytes, Class<T> resultType) {
        if (SerializationUtils.isEmpty(bytes)) {
            return null;
        }

        if (Arrays.equals(getNullValueBytes(), bytes)) {
            return null;
        }
        return JSON.parseObject(new String(bytes, IOUtils.UTF8), resultType, DEFAULT_REDIS_CONFIG, FEATURES);
    }

}